package com.dzwww.recommend.rule.service.aspect;

import com.dzwww.recommend.rule.common.constant.CommonErrorMessage;
import com.dzwww.recommend.rule.util.validator.ValidatorGroup;
import com.dzwww.recommend.rule.util.validator.ValidatorUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * Service校验切面
 * <p>
 * 注意Order：设置order为负数，最先被执行
 * <p>
 *   @author lixin
 *   @date 2018/3/31 下午1:29
 *   @version 1.0
 */
@Component
@Aspect
@Order(-1)
@EnableAspectJAutoProxy(proxyTargetClass = true, exposeProxy = true)
public class ServiceVerifyAspect {

    /**
     * add前的验证
     */
    @Around("execution(* com.dzwww.recommend.rule.service.base.BaseService.add(..))")
    public Object addVerify(ProceedingJoinPoint pjd) throws Throwable {
        List<Object> argList = Arrays.asList(pjd.getArgs());

        // 验证
        ValidatorUtils.validateParseException(argList.get(0), ValidatorGroup.Add.class);

        return pjd.proceed();
    }

    /**
     * update前的验证
     */
    @Around("execution(* com.dzwww.recommend.rule.service.base.BaseService.modifyById(..))")
    public Object updateVerify(ProceedingJoinPoint pjd) throws Throwable {
        List<Object> argList = Arrays.asList(pjd.getArgs());

        // 验证
        ValidatorUtils.validateParseException(argList.get(0), ValidatorGroup.Update.class);

        return pjd.proceed();
    }

    /**
     * delete前的验证
     */
    @Around("execution(* com.dzwww.recommend.rule.service.base.BaseService.delById(..))")
    public Object deleteVerify(ProceedingJoinPoint pjd) throws Throwable {
        List<Object> argList = Arrays.asList(pjd.getArgs());

        Object id = argList.get(0);
        if (Objects.isNull(id)) {
            throw CommonErrorMessage.VERIFY_ERROR.addMsg("ID不能为空").toException();
        } else {
            return pjd.proceed();
        }
    }

}
